package com.nx.biz.shopify.sdk.ShopifySdk;

import com.google.gson.Gson;
import com.nx.biz.shopify.sdk.ShopifySdk.model.bo.WebHookBo;
import com.nx.biz.shopify.sdk.ShopifySdk.model.bo.WebHookBoRoot;
import com.nx.biz.shopify.sdk.ShopifySdk.model.bo.WebHookBosRoot;
import com.nx.biz.shopify.sdk.ShopifySdk.model.cmd.WebhookCreateReq;
import com.nx.biz.shopify.sdk.ShopifySdk.model.constant.UrlConstant;
import com.nx.biz.shopify.tools.HttpRestClientTool;
import com.nx.common.result.HttpClientResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class WebhooksSdk {

    protected static final Gson GSON = new Gson();
//    public static String restUrlTemplate = "https://%s.myshopify.com/admin/api/2024-04/webhooks.json";
//    public static String restUrlInstTemplate = "https://%s.myshopify.com/admin/api/2024-04/webhooks/%s.json";
//
//    public static String token = "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";
//    public static String devStoreNo = "track-dev-0704";

    public WebHookBo queryTopic(String id, String shopDomain, String apiVersion, String accessToken) throws IOException {
        /** 1. 参数初始化 */
//        String url = String.format(restUrlInstTemplate, devStoreNo, id);
        String url = String.format(UrlConstant.webhookInstRestUrl, shopDomain, apiVersion, id);
//        CarrierServiceCreateReq carrierServiceCreateReq = new CarrierServiceCreateReq();
//        carrierServiceCreateReq.setTopic(topic);
//        carrierServiceCreateReq.setCallback_url(callBackUrl);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("X-Shopify-Access-Token", accessToken);

        /** 2. 发送请求 */
        HttpClientResult clientResult = HttpRestClientTool.sendGet(url, "UTF-8", headers);
        log.info("response: {}", GSON.toJson(clientResult));
        if (clientResult.getCode() != 200) {
            log.error("错误，返回code {}", clientResult.getCode());
            return null;
        }

        /** 3. 解析返回值 */
        String content = clientResult.getContent();
        WebHookBoRoot webHookBoRoot = GSON.fromJson(content, WebHookBoRoot.class);

        /** 4. 存储到db中 */

        return webHookBoRoot.getWebhook();
    }

    public List<WebHookBo> listTopic(String shopDomain, String apiVersion, String accessToken) throws IOException {
        /** 1. 参数初始化 */
//        String url = String.format(restUrlTemplate, devStoreNo);
        String url = String.format(UrlConstant.webhookRestUrl, shopDomain, apiVersion);
//        CarrierServiceCreateReq carrierServiceCreateReq = new CarrierServiceCreateReq();
//        carrierServiceCreateReq.setTopic(topic);
//        carrierServiceCreateReq.setCallback_url(callBackUrl);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("X-Shopify-Access-Token", accessToken);

        /** 2. 发送请求 */
        HttpClientResult clientResult = HttpRestClientTool.sendGet(url, "UTF-8", headers);
        if (clientResult.getCode() != 200) {
            log.error("错误，返回code {}", clientResult.getCode());
            return null;
        }

        /** 3. 解析返回值 */
        String content = clientResult.getContent();
        WebHookBosRoot webHookBosRoot = GSON.fromJson(content, WebHookBosRoot.class);

        /** 4. 存储到db中 */

        return webHookBosRoot.getWebhooks();
    }

    public WebHookBo createTopic(String topic, String callBackUrl, String shopDomain, String apiVersion, String accessToken) throws IOException {
        /** 1. 参数初始化 */
//        String url = String.format(restUrlTemplate, devStoreNo);
        String url = String.format(UrlConstant.webhookRestUrl, shopDomain, apiVersion);
        WebhookCreateReq webhookCreateReq = new WebhookCreateReq();
        webhookCreateReq.getWebhook().setTopic(topic);
        webhookCreateReq.getWebhook().setAddress(callBackUrl);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("X-Shopify-Access-Token", accessToken);

        /** 2. 发送请求 */
        HttpClientResult clientResult = HttpRestClientTool.post(url, GSON.toJson(webhookCreateReq), "application/json", headers);
        if (clientResult.getCode() != 201) {
            log.error("订阅webhook请求响应有误，返回信息：{}", GSON.toJson(clientResult));
            return null;
        }

        /** 3. 解析返回值 */
        String content = clientResult.getContent();
        WebHookBoRoot webHookBoRoot = GSON.fromJson(content, WebHookBoRoot.class);

        /** 4. 存储到db中 */

        return webHookBoRoot.getWebhook();
    }

    public void deleteTopic(String id, String shopDomain, String apiVersion, String accessToken) throws IOException {
        /** 1. 参数初始化 */
//        String url = String.format(restUrlInstTemplate, devStoreNo, id);
        String url = String.format(UrlConstant.webhookInstRestUrl, shopDomain, apiVersion, id);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("X-Shopify-Access-Token", accessToken);

        /** 2. 发送请求 */
        HttpClientResult clientResult = HttpRestClientTool.sendDel(url, "UTF8", headers);
        if (clientResult.getCode() != 200) {
            log.error("错误，返回code {}", clientResult.getCode());
        }
    }

//    public void onFulfillmentCreate(WebHookHeaderBo webHookHeaderBo, WhFulfillmentCreatePayload respPayload) {
//        // 1. 缓存 订单-运单的关系到redis中
//        redisUtil.hset(RedisKeys.shopifyFulfillment, String.valueOf(respPayload.getOrder_id()), respPayload);
//
//        // 2.
//    }
//
//    public void onInit() throws Exception {
//        // 1，查询订阅的topic
//        List<WebHookBo> webHookBoList = listTopic();
//
//        // 2. 判断已订阅
//        Boolean found = false;
//        for (WebHookBo webHookBo : webHookBoList) {
//            if (webHookBo.getTopic().equals(TopicConstants.fulfillmentCreate)) {
//                found = true;
//                break;
//            }
//        }
//        // 3. 如果未注册，则订阅
//        if (!found) {
//            WebHookBo webHookBo = createTopic(TopicConstants.fulfillmentCreate, "callback url");
//            if (webHookBo == null) {
//                throw new BusinessException(String.format("订阅topic %s 失败", TopicConstants.fulfillmentCreate));
//            }
//        }
//    }
//
//    public void onCallback(WebHookHeaderBo webHookHeaderBo, String payLoad) {
//        if (webHookHeaderBo.getTopic().equals(TopicConstants.fulfillmentCreate)) {
//            WhFulfillmentCreatePayload respPayload = GSON.fromJson(payLoad, WhFulfillmentCreatePayload.class);
//            onFulfillmentCreate(webHookHeaderBo, respPayload);
//        } else {
//            log.error("收到未识别的webhook event, header:{},  topic: {}", webHookHeaderBo, payLoad);
//        }
//    }


//    String serverUrl = "http://localhost:8080/graphql";
//
//    public void post() {
//        //build一个新的graphqlclient
//        GraphqlClient graphqlClient = GraphqlClient.buildGraphqlClient(serverUrl);
//
//        //如果说graphql需要健全信息我们可以用map来进行传递
//        Map<String,String> httpHeaders = new HashMap<>();
//        httpHeaders.put("token","graphqltesttoken");
//        //设置http请求的头
//        graphqlClient.setHttpHeaders(httpHeaders);
//        //发起一个简单的query查询
//
//        //创建一个Query并设置query的名字为findUser
//        //如果有特殊需要可以自己继承GraphqlQuery,DefaultGraphqlQuery已经可以满足所有请求了
//        GraphqlQuery query = new DefaultGraphqlQuery("findUser");
//
//        // 设置参数
//        query.addParameter("name","张三").addParameter("age",23);
//
//        //我们需要查询user的名字，性别还有年龄，设置需要查询的这三个属性。
//        query.addResultAttributes("name","sex","age");
//
//        try {
//            //执行query
//            GraphqlResponse response = graphqlClient.doQuery(query);
//            //获取数据，数据为map类型
//            Map result = response.getData();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//    }
////
////    // 创建GraphQLSchema
////    public static GraphQLSchema createGraphQLSchema(GraphQLFieldDefinition userDefinition) {
////        GraphQLObjectType userQuery = GraphQLObjectType.newObject()
////                .name("userQuery")
////                .field(userDefinition)
////                .build();
////        return GraphQLSchema.newSchema().query(userQuery).build();
////    }
////
////    /**
////     * 创建GraphQLFieldDefinition对象
////     *
////     * 根据定义的查询对象做真正的查询，返回查询数据
////     *
////     * 这里使用静态对象构建数据，如果是查询数据，可以在这里进行做查询
////     *
////     */
////    public static GraphQLFieldDefinition createGraphQLFieldDefinition(GraphQLObjectType userType) {
////        return GraphQLFieldDefinition.newFieldDefinition()
////                .name("User")
////                .type(userType)
////                // 设置参数查询数据
////                .argument(GraphQLArgument.newArgument().name("id").type(Scalars.GraphQLInt).build())
////                .dataFetcher(environment -> {
////                    Long id = environment.getArgument("id");
////                    return new User(id, "name" + id, id.intValue());
////                })
////                .build();
////    }
////
////    /**
////     * 定义GraphQLObjectType对象
////     * 该对象是用来做查询响应对象的名称和查询的字段的定义
////     */
////    public static GraphQLObjectType createGraphQLObjectType() {
////        return GraphQLObjectType.newObject()
////                .name("User")
////                .field(GraphQLFieldDefinition.newFieldDefinition().name("id").type(Scalars.GraphQLInt))
////                .field(GraphQLFieldDefinition.newFieldDefinition().name("name").type(Scalars.GraphQLString))
////                .field(GraphQLFieldDefinition.newFieldDefinition().name("age").type(Scalars.GraphQLInt))
////                .build();
////    }
////
////    public static void main(String[] args) {
////        GraphQLObjectType userType = createGraphQLObjectType();
////        GraphQLFieldDefinition userDefinition = createGraphQLFieldDefinition(userType);
////        GraphQLSchema graphQLSchema = createGraphQLSchema(userDefinition);
////        GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build();
////
////        String graph3 = "{User(id:1){id, name, age}}";
////        ExecutionResult execute3 = graphQL.execute(graph3);
////        // 获取结果
////        System.out.println(execute3.toSpecification());
////    }
}
